import dict from '../core/dict';
import cardItem from './cardItem';
import utils from '../core/utils';
import logger from '../core/logger';
import videoClient from '../http/videoClient';
import common from '@ohos.app.ability.common';
import relationalStore from '@ohos.data.relationalStore';
import { globalData } from '../core/globalData';

export default class serviceCache {
  private context: common.Context;
  private static _instance: serviceCache;

  private constructor(context: common.Context) {
    this.context = context;
    this.init();
  }

  public static get instance(): serviceCache {
    return this._instance;
  }

  public static createInstance(context: common.Context): serviceCache {
    if (this._instance == null)
      this._instance = new serviceCache(context);
    return this._instance;
  }

  private get rdbStore() {
    return globalData.cardRdbStore;
  }

  private async init() {
    try {
      if (utils.isEmpty(this.rdbStore)) {
        await relationalStore.getRdbStore(this.context, dict.STORE_CARD_CONFIG).then((rdbStore: relationalStore.RdbStore) => {
          if (!utils.isEmpty(rdbStore)) {
            rdbStore.executeSql(dict.CARD_TABLE_FORM);
            globalData.cardRdbStore = rdbStore;
          }
        });
      }
    } catch (e) {
      logger.error(e);
    }
  }

  private clear() {
    try {
      let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.CARD_TABLE_NAME);
      this.rdbStore.delete(predicates);
    } catch (e) {
      logger.error(e);
    }
  }

  public loadData() {
    try {
      videoClient.getHot(1, '').then((res) => {
        if (res.success) {
          if (res.data?.code == 0 && res.data?.data.length > 0) {
            this.clear();
            res.data.data.forEach((i) => {
              let obj = {
                cid: i.param,
                name: i.title,
                cover: i.cover,
                desc: `${i.right_desc_1}${i.right_desc_2}`
              };
              this.rdbStore.insert(dict.CARD_TABLE_NAME, obj);
            });
          }
        } else
          utils.showPopup(res.msg);
      });
    } catch (e) {
      logger.error(e);
    }
  }

  public getListData(): Promise<cardItem[]> {
    return new Promise((resolve) => {
      let array = [];
      try {
        let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates(dict.CARD_TABLE_NAME);
        this.rdbStore.query(predicates).then((resultSet: relationalStore.ResultSet) => {
          if (resultSet.rowCount > 0) {
            resultSet.goToFirstRow();
            do {
              let cid: string = resultSet.getString(resultSet.getColumnIndex('cid'));
              let name: string = resultSet.getString(resultSet.getColumnIndex('name'));
              let cover: string = resultSet.getString(resultSet.getColumnIndex('cover'));
              let desc: string = resultSet.getString(resultSet.getColumnIndex('desc'));
              array.push(new cardItem(cid, name, cover, desc));
            } while (resultSet.goToNextRow());
            resultSet.close();
          }
          resolve(array);
        }).catch((res) => {
          logger.error(res);
          resolve(array);
        });
      } catch (e) {
        logger.error(e);
        resolve(array);
      }
    });
  }

  private toFormData(dataSource: cardItem[]): Promise<object> {
    return new Promise((resolve) => {
      let formData = {};
      try {
        if (!utils.isEmpty(dataSource) && dataSource.length > 0) {
          let length = dataSource.length;
          let start = utils.getRandomInt(length);
          if (start >= length) start = 0;
          let item = dataSource[start];
          let end = start + 1;
          if (end >= length) end = 0;
          let last = dataSource[end];
          utils.buildMemoryImage(this.context, [item?.cover, last?.cover]).then((res) => {
            let fileInfo = {};
            let imageName = res[0].fileName, lastImageName = res[1].fileName;
            fileInfo[imageName] = res[0].fileId;
            fileInfo[lastImageName] = res[1].fileId;
            formData = {
              'cid': item.cid,
              'last_cid': last.cid,
              'title': item.name,
              'last_title': last.name,
              'describe': item.desc,
              'last_describe': last.desc,
              'formImages': fileInfo,
              'image': `memory://${imageName}`,
              'last_image': `memory://${lastImageName}`
            };
            resolve(formData);
          });
        } else
          resolve(formData);
      } catch (e) {
        logger.error(e);
        resolve(formData);
      }
    });
  }

  public getFormData(dataSource: cardItem[]): Promise<object> {
    return new Promise((resolve) => this.toFormData(dataSource).then((res) => resolve(res)));
  }
}